/*****************************************************************************
* Project:  avr-iic-driver
*
* Copyright (C) 2013 Bill Wu. All rights reserved.
*
* This program is open source software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* Alternatively, this program may be distributed and modified under the
* terms of Quantum Leaps commercial licenses, which expressly supersede
* the GNU General Public License and are specifically designed for
* licensees interested in retaining the proprietary status of their code.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* e-mail:               wushangru@student.hlju.edu.cn
*****************************************************************************/

#ifndef IIC_HD_H_
#define IIC_HD_H_

#include <avr/io.h>

/** state code, also define in TWI.h */
#define TW_STATUS_MASK		(_BV(TWS7)|_BV(TWS6)|_BV(TWS5)|_BV(TWS4)|\
				             _BV(TWS3))
#define TW_STATUS		    (TWSR & TW_STATUS_MASK)

#define TW_START		    0x08
#define TW_REP_START		0x10
#define TW_MT_SLA_ACK		0x18
#define TW_MT_SLA_NACK		0x20
#define TW_MT_DATA_ACK		0x28
#define TW_MT_DATA_NACK		0x30
#define TW_MR_SLA_ACK		0x40
#define TW_MR_SLA_NACK		0x48
#define TW_MR_DATA_ACK		0x50
#define TW_MR_DATA_NACK		0x58
#define TW_ST_SLA_ACK		0xA8


/** IIC operation by hardware */
                                        /* wait hardware to complete action */
#define WAIT()        while((TWCR & (1<<TWINT)) == 0)
#define START()       (TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN))
#define STOP()        (TWCR = (1<<TWINT) | (1<<TWSTO) | (1<<TWEN))
#define ACK()         (TWCR |=  (1<<TWEA))
#define NACK()        (TWCR &= ~(1<<TWEA))
#define TWI_BEGIN()   (TWCR = (1<<TWINT) | (1<<TWEN))          /* start TWI */
#define WRITE_BYTE(x) do { \
                          TWDR = (x); \
                          TWCR = (1<<TWINT) | (1<<TWEN); \
                      } while(0)
/*..........................................................................*/

#define WR                        0x00
#define RD                        0x01
#define EN_PULL_UP_RESISTOR()     (PORTC |= (1<<PC0) | (1<<PC1))


#endif /* IIC_HD_H_ */

